// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var router = require("../hash/pageRouter");
	var tools = require("tools");
	var fileUuid = [];
	var css_product = require("./productAdd.css");
	var productId = "";
	var copyState;
	var init = function(page) {
		if (page.params != null) {
			productId = page.params.productId;
			copyState = page.params.copyState;
			tools.requireInput($("#productAdd"));
			if (productId != null) {
				databind.fillInput($("#productAdd"), {
					action: "inquireFinanceProductDetail.json?productId=" + productId,
					async: false
				});
				autocomplete();
				var fs = $("#productIntroUuid").val().split(",");
				for (var j = 0; j < fs.length; j++) {
					if ($.trim(fs[j]) != "") {
						$("#productAdd .fs").append('<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + fs[j] + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + fs[j] + '" class="showProductIntro">'+ tools.inquireFile(fs[j]) +'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>');
					}
				}
				var fs = $("#productIntroUuid1").val().split(",");
				for (var j = 0; j < fs.length; j++) {
					if ($.trim(fs[j]) != "") {
						$("#productAdd .fs1").append('<div class="showProductIntroDiv1"><a target="_blank" class="mas" fileUuid="' + fs[j] + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + fs[j] + '" class="showProductIntro">'+ tools.inquireFile(fs[j]) +'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>');
					}
				}
			}
			
			if ($("#productAdd .bail:checked").val() == 1) {
				$("#productAdd .bailRate").removeClass("none");
			} else {
				$("#productAdd .bailRate").addClass("none");
			}
		}
		router.init();
		initEvent();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}

		autocomplete();

		$("#productAdd").on("change", "#productIntro", function() {
			uploadFile();
		});
		
		$("#productAdd").on("change", "#productIntro1", function() {
			uploadFile1();
		});
		
		$("#productAdd").on("change", "#productIntro2", function() {
			tools.uploadFile("productIntro2", function(data){
				$(".productIntro2").html(data.data[0].fileName);
				$("#productIntroUuid2").val(data.data[0].fileUuid);
			});
		});
		
		$("#productAdd").on("change", "select[name=loanMethod]", function() {
			if ($(this).val() ==1) {
				$("#productAdd input[name=baseDays]").parent().removeClass("none").addClass("requireInput");
				$("#productAdd input[name=baseDays]").attr("isNull", "1");
			} else {
				$("#productAdd input[name=baseDays]").parent().addClass("none").removeClass("requireInput");
				$("#productAdd input[name=baseDays]").attr("isNull", "0");
			}
		});

		$("#productAdd").on("click", ".showProductIntroDiv .deleteProductIntro", function() {
			$(this).parent().remove();
			fileUuid = [];
			for (var j = 0; j < $("#productAdd .showProductIntroDiv .mas").length; j++) {
				fileUuid.push($($("#productAdd .showProductIntroDiv .mas")[j]).attr("fileUuid"));
			}
			$("#productIntroUuid").val(fileUuid);
		});
		
		$("#productAdd").on("click", ".showProductIntroDiv1 .deleteProductIntro", function() {
			$(this).parent().remove();
			fileUuid = [];
			for (var j = 0; j < $("#productAdd .showProductIntroDiv1 .mas").length; j++) {
				fileUuid.push($($("#productAdd .showProductIntroDiv1 .mas")[j]).attr("fileUuid"));
			}
			$("#productIntroUuid1").val(fileUuid);
		});

		//返回产品管理列表
		$(".productManage").unbind("click").click(function() {
			router.route("productManage/productManage.html");
		});

		$("#productAdd").on("click", ".bail", function() {
			if ($(this).val() == 1 || $(this).val() == "true") {
				$("#productAdd .bailRate").removeClass("none");
				$("#productAdd .bailRate input").val(0);
			} else {
				$("#productAdd .bailRate").addClass("none");
				$("#productAdd .bailRate input").val("");
			}
		});

		$("#productNext").unbind("click").click(function() {

			var sDate = new Date($("#startDate1").val().replace(/-/g, "//"));
			var eDate = new Date($("#endDate1").val().replace(/-/g, "//"));
			if ($("#interest").val() > 100) {
				base.alert(2, "产品费率不能超过100！");
			} else if (sDate > eDate) {
				base.alert(2, "结束日期不能小于开始日期！");

			} else if (parseInt($("#minDays1").val()) > parseInt($("#maxDays1").val())) {
				base.alert(2, "结束天数不能小于开始天数！");
			} else {
				if ($("#productEnterpriseId").val() == 0) {
					$("#productEnterpriseId").val("");
				}
				if (productId != null) {
					if (copyState == 1) {
						databind.submitDom($("#productAdd"), function(data) {
							router.route("productManage/productCharge.html?productId=" + data.datas[0].productId);
						});
					} else {
						$("#productAdd").attr("action", "updateFinanceProduct");
						databind.submitDom($("#productAdd"), function(data) {
							router.route("productManage/productCharge.html?productId=" + productId);
						});
					}
				} else {
					databind.submitDom($("#productAdd"), function(data) {
						router.route("productManage/productCharge.html?productId=" + data.datas[0].productId);
					});
				}
			}
		});

	};

	var autocomplete = function() {
		//自动补全
		$("#productEnterpriseName").autocomplete(seajs.data.handler + "inquireEnterprisePageList.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				enterpriseName: function() {
					return $("#productEnterpriseName").val();
				},
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid")
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.enterpriseName, //此处无需把全部列列出来，只是两个关键列
						result: row.enterpriseName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#productEnterpriseName").hasClass('nonemorelist')) {
					$("#productEnterpriseName").removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.enterpriseName + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.enterpriseName;
			},
			formatResult: function(data, value) {
				return data.enterpriseName;
			}
		}).result(function(event, data, formatted) { //回调 
			$('#productEnterpriseName').val(data.enterpriseName);
			if ($("#productEnterpriseName").hasClass('nonemorelist')) {
				$("#productEnterpriseName").removeClass('nonemorelist');
			} else {
				$("#productEnterpriseName").addClass('nonemorelist');
			};
			$("#productEnterpriseId").val(data.enterpriseId);
		});
	};

	//上传文件
	var uploadFile = function() {
		if ($("#productIntro").val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: 'productIntro',
				dataType: 'json',
				success: function(data) {
					var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '" class="showProductIntro">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>'
					$(".productIntro").before(str);
					fileUuid = [];
					for (var j = 0; j < $(".showProductIntroDiv .mas").length; j++) {
						fileUuid.push($($(".showProductIntroDiv .mas")[j]).attr("fileUuid"));
					}
					$("#productIntroUuid").val(fileUuid);
				},
				complete: function(xml) {
					$("#productIntro").change(function() {
						uploadFile();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};
	
	//上传文件
	var uploadFile1 = function() {
		if ($("#productIntro1").val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: 'productIntro1',
				dataType: 'json',
				success: function(data) {
					var str = '<div class="showProductIntroDiv1"><a target="_blank" class="mas" fileUuid="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '" class="showProductIntro">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>'
					$(".productIntro1").before(str);
					fileUuid = [];
					for (var j = 0; j < $(".showProductIntroDiv1 .mas").length; j++) {
						fileUuid.push($($(".showProductIntroDiv1 .mas")[j]).attr("fileUuid"));
					}
					$("#productIntroUuid1").val(fileUuid);
				},
				complete: function(xml) {
					$("#productIntro1").change(function() {
						uploadFile1();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};

	return {
		init: init
	};
});